package cn.zf233.springsecurityjwt.web;

import cn.zf233.springsecurityjwt.common.R;
import cn.zf233.springsecurityjwt.entity.User;
import cn.zf233.springsecurityjwt.service.UserService;
import cn.zf233.springsecurityjwt.util.JwtUtil;
import cn.zf233.springsecurityjwt.util.TestVCodePool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * Created by zf233 on 2021/7/12
 */
@Slf4j
@RestController
public class LoginController {

    @Resource
    private JwtUtil jwtUtil;

    @Resource
    private UserService userService;

    @PostMapping("/login")
    public R<String> login(User user) {
        log.info("开始进行账号密码登陆:" + user);
        return R.createByError();
    }

    @PostMapping("/login/phone")
    public R<String> loginPhone(User user, String code) {
        log.info("开始进行手机验证码登陆:" + user);
        return R.createByError();
    }

    @GetMapping("/login/code")
    public R<String> code(User user) {
        log.info("获取手机验证码:" + user);
        User result = userService.getUserByPhone(user.getPhone());
        if (result != null) {
            String code = getVCode();
            TestVCodePool.Set(result.getPhone(), code);
            log.info("获取手机验证码成功:'" + code + "'");
            return R.createBySuccess("手机验证码获取成功", code);
        }
        log.info("用户不存在，获取验证码失败");
        return R.createByErrorMessage("用户不存在");
    }

    @PostMapping("/login/open")
    public R<String> loginOpen(User user) {
        log.info("开始进行社交登陆:" + user);
        return R.createByError();
    }

    private String getVCode() {
        log.info("生成验证码");
        StringBuilder code = new StringBuilder();
        // 这里的code可以存入redis
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            code.append(random.nextInt(10));
        }
        return code.toString();
    }

    @RequestMapping("/fail")
    public R<String> loginFail() {
        return R.createByErrorMessage("登陆失败");
    }

    @RequestMapping("/success")
    public R<String> loginSuccess(Authentication authentication) {
        String token = jwtUtil.createTokenByUserId(Long.parseLong((String) authentication.getPrincipal()), TimeUnit.DAYS.toMillis(7L));
        return R.createBySuccess("登陆成功", token);
    }
}
